package com.cjx.print.ui;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.cjx.print.App;
import com.cjx.print.BackgroundService;
import com.cjx.print.Constants;
import com.cjx.print.R;
import com.jeremyliao.liveeventbus.LiveEventBus;

import net.posprinter.POSConnect;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * create by cjx on 2024/9/6
 * desc:
 */
public class MainActivity extends AppCompatActivity {

    private final int REQUEST_PERMISSION_CODE = 1000;
    private final String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,};

    TextView titleView;
    TextView modeView;
    TextView typeView;
    TextView connectView;
    ProgressBar progressBar;
    View modeContainer;
    View typeContainer;

    TextView receiptTitleView;
    TextView receiptModeView;
    TextView receiptTypeView;
    TextView receiptConnectView;
    ProgressBar receiptProgressBar;
    View receiptModeContainer;
    View receiptTypeContainer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ArrayList<String> permissions = new ArrayList<>();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (!permissions.isEmpty()) {
                requestPermissions(permissions.toArray(new String[0]), REQUEST_PERMISSION_CODE);
            } else {
                init();
            }
        } else {
            init();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            boolean flagt = false;
            for (int i = 0; i < permissions.length; i++) {
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    flagt = true;
                    break;
                }
            }
            if (flagt) {//授权失败
                finish();
            } else {
                init();
            }
        }
    }

    private void init() {
        titleView = findViewById(R.id.title);
        connectView = findViewById(R.id.connect);
        progressBar = findViewById(R.id.progress);
        modeView = findViewById(R.id.mode);
        typeView = findViewById(R.id.type);
        modeContainer = findViewById(R.id.mode_container);
        typeContainer = findViewById(R.id.type_container);
        if (!TextUtils.isEmpty(App.app.tagName)) {
            titleView.setText("标签机（" + App.app.tagName + "）");
            modeView.setText(App.app.tagName);
            typeView.setText(App.app.tagType);
        }
        modeContainer.setOnClickListener(v -> {
            SingleSelectDialogFragment.newInstance("选择标签机", getTagPrinterItems(), item -> {
                modeView.setText(item.name);
                modeView.setTag(item.key);
                int m = Integer.parseInt(item.key);
                if (Constants.MODE_TAG_JC_B3S == m) {
                    typeView.setText("蓝牙");
                    typeView.setTag("0");
                }
            }).show(getSupportFragmentManager(), "mode");
        });
        typeContainer.setOnClickListener(v -> {
            SingleSelectDialogFragment.newInstance("连接方式", getTagTypeItems(), item -> {
                typeView.setText(item.name);
                typeView.setTag(item.key);
            }).show(getSupportFragmentManager(), "type");
        });
        connectView.setOnClickListener(v -> {
            connectView.setText(null);
            connectView.setEnabled(false);
            progressBar.setVisibility(View.VISIBLE);

            receiptConnectView.setEnabled(false);
            startService();
        });

        receiptTitleView = findViewById(R.id.title_receipt);
        receiptConnectView = findViewById(R.id.connect_receipt);
        receiptProgressBar = findViewById(R.id.progress_receipt);
        receiptModeView = findViewById(R.id.mode_receipt);
        receiptTypeView = findViewById(R.id.type_receipt);
        receiptModeContainer = findViewById(R.id.mode_container_receipt);
        receiptTypeContainer = findViewById(R.id.type_container_receipt);
        if (!TextUtils.isEmpty(App.app.receiptName)) {
            receiptTitleView.setText("小票机（" + App.app.receiptName + "）");
            receiptModeView.setText(App.app.receiptName);
            receiptTypeView.setText(App.app.receiptType);
        }
        receiptModeContainer.setOnClickListener(v -> {
            SingleSelectDialogFragment.newInstance("选择小票机", getReceiptPrinterItems(), item -> {
                receiptModeView.setText(item.name);
                receiptModeView.setTag(item.key);
            }).show(getSupportFragmentManager(), "receipt_mode");
        });
        receiptTypeContainer.setOnClickListener(v -> {
            SingleSelectDialogFragment.newInstance("连接方式", getTagTypeItems(), item -> {
                receiptTypeView.setText(item.name);
                receiptTypeView.setTag(item.key);
            }).show(getSupportFragmentManager(), "receipt_type");
        });
        receiptConnectView.setOnClickListener(v -> {
            receiptConnectView.setText(null);
            receiptConnectView.setEnabled(false);
            receiptProgressBar.setVisibility(View.VISIBLE);

            connectView.setEnabled(false);
            startService();
        });


        LiveEventBus.get(App.BUS_CONNECT, Boolean.class).observe(this, o -> {
            if (progressBar.getVisibility() == View.VISIBLE) {
                connectView.setText("连接");
                connectView.setEnabled(true);
                progressBar.setVisibility(View.GONE);
                receiptConnectView.setEnabled(true);
                if (o != null && o) {
                    Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    App.app.tagName = modeView.getText().toString();
                    App.app.tagType = typeView.getText().toString();
                    titleView.setText("标签机（" + App.app.tagName + "）");
                }else{
                    titleView.setText("标签机（）");
                }
            } else {
                receiptConnectView.setText("连接");
                receiptConnectView.setEnabled(true);
                receiptProgressBar.setVisibility(View.GONE);
                connectView.setEnabled(true);
                if (o != null && o) {
                    Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_SHORT).show();
                    App.app.receiptName = receiptModeView.getText().toString();
                    App.app.receiptType = receiptTypeView.getText().toString();
                    receiptTitleView.setText("小票机（" + App.app.receiptName + "）");
                }
            }
        });
    }

    private List<SingleSelectDialogFragment.ItemEntity> getTagPrinterItems() {
        return Arrays.asList(
                new SingleSelectDialogFragment.ItemEntity("精臣 B3S系列", String.valueOf(Constants.MODE_TAG_JC_B3S), null),
                new SingleSelectDialogFragment.ItemEntity("芯烨 XP-T271U", String.valueOf(Constants.MODE_TAG_XY_T271U), null)
        );
    }

    private List<SingleSelectDialogFragment.ItemEntity> getReceiptPrinterItems() {
        return Collections.singletonList(
                new SingleSelectDialogFragment.ItemEntity("芯烨 XP-N160II", String.valueOf(Constants.MODE_TAG_XY_N160II), null)
        );
    }

    private List<SingleSelectDialogFragment.ItemEntity> getTagTypeItems() {
        if ("0" .equals(modeView.getTag())) {
            return Collections.singletonList(
                    new SingleSelectDialogFragment.ItemEntity("蓝牙", "0", null)
            );
        }
        List<String> usbDevices = POSConnect.getUsbDevices(App.app);
        ArrayList<SingleSelectDialogFragment.ItemEntity> items = new ArrayList<>(usbDevices.size() + 1);
        items.add(new SingleSelectDialogFragment.ItemEntity("蓝牙", "0", null));
        for (String path : usbDevices) {
            items.add(new SingleSelectDialogFragment.ItemEntity(path, path, null));
        }
        return items;
    }

    private void startService() {
        System.out.println("MainActivity 启动后台服务");
        Intent severIntent = new Intent(this, BackgroundService.class);
        if (progressBar.getVisibility() == View.VISIBLE) {
            severIntent.putExtra("tag", (String) modeView.getTag());
            severIntent.putExtra("type", (String) typeView.getTag());
        } else {
            severIntent.putExtra("receipt", (String) receiptModeView.getTag());
            severIntent.putExtra("type", (String) receiptTypeView.getTag());
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(severIntent);
        } else {
            startService(severIntent);
        }
    }


}
